package com.hrc.springbootdemo.minio;

import io.minio.BucketExistsArgs;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.http.Method;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.concurrent.TimeUnit;

@Service
public class MinioService {

    @Resource
    private MinioClient minioClient;

    @Value("${minio.bucketName}")
    private String bucketName;


    /**
     * 创建存储桶（如果不存在）
     * @throws Exception 如果创建存储桶时发生错误则抛出异常
     */
    public void createBucket() throws Exception {
        minioClient.listBuckets(); // 强制刷新 bucket 列表
        boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (!exists) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
    }

    public String uploadFile(String objectName, MultipartFile file) throws Exception {
        createBucket();
        minioClient.putObject(
            PutObjectArgs.builder().bucket(bucketName).object(objectName)
                .stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build());
        return getPresignedUrl(objectName);
    }

    /**
     * 获取预签名的URL用于访问指定的对象
     * 预签名的URL允许在限定时间内无密钥访问该对象
     *
     * @param objectName 对象名称，用于标识存储在MinIO服务器上的文件
     * @return 返回预签名的URL字符串，用于访问指定的对象
     * @throws Exception 如果生成预签名URL时发生错误，则抛出异常
     */
    public String getPresignedUrl(String objectName) throws Exception {
        return minioClient.getPresignedObjectUrl(
                GetPresignedObjectUrlArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .method(Method.GET)
                        .expiry(7, TimeUnit.DAYS)
                        // 添加响应头以强制下载
                        .extraQueryParams(java.util.Map.of("response-content-disposition", "attachment"))
                        .build());
    }

}